package com.twinkle.dbmanage.util;

import com.twinkle.dbmanage.vo.DBConfig;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author Twinkle
 */
public class DBUtil {
    private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";

    /**
     * 获取连接
     *
     * @return 数据库连接
     */
    public static Connection getConnection(DBConfig config) {
        Connection conn = null;
        try {
            Class.forName(DATABASE_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            if (config != null) {
                conn = DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭连接
     *
     * @param resultSet  待关闭的结果集
     * @param statement  待关闭的 SQL 编译对象
     * @param connection 待关闭的数据库连接
     */
    public static void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {

                try {
                    if (connection != null) {
                        connection.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
